const express = require('express')
const { md5Pwd } = require('../utils')
const model = require('../model')
const omit = require('omit.js')
const User = model.getModel('user')
const router = express.Router()

const filter = { password: 0, __v: 0 }

router.get('/remove', (req, res, next) => {
    const { username } = req.query
    let condition = {}
    if(username) condition.username = username
    User.remove(condition, (err, doc) => {
        if(err)
            return next(err)
        res.json(doc)
    })
})

router.get('/data', (req, res, next) => {
    const { type } = req.query
    let conditions = {}
    if(type) conditions.type = type
    User.find(conditions, filter, (err, doc) => {
        if(err) return next(err)
        res.json({code: 0, data: doc})
    })
})

router.post('/login', (req, res, next) => {
    const { username, password } = req.body
    User.findOne({ username, password: md5Pwd(password) }, filter, (err, doc) => {
        if(err)
            return next(err)
        if(!doc)
            return res.json({ code: 1, message: '用户名或密码不存在' })
        res.cookie('type', doc.type)
        res.cookie('userId', doc._id)
        return res.json({ code: 0, message: '登录成功', user: doc._doc })
    })
})

router.post('/register', (req, res, next) => {
    const { username, password, type } = req.body
    User.findOne({ username }, (err, doc) => {
        if(err)
            return next(err)
        if(doc)
            return res.json({ code: 1, message: '用户名重复' })
        User.create({ username, type, password: md5Pwd(password) }, (err, doc) => {
            if(err)
                return next(err)
            res.cookie('type', doc.type)
            res.cookie('userId', doc._id)
            res.json({ code: 0, message: '注册成功', user: omit(doc._doc, Object.keys(filter)) })
        })
    })
})

router.get('/auth', (req, res, next) => {
    const { userId } = req.cookies
    if(!userId)
        return res.json({code: 1})
    User.findOne({ _id: userId }, filter, (err, doc) => {
        if(err) return next(err)
        res.json({code: 0, user: doc._doc})
    })
})

router.post('/update', (req, res, next) => {
    const { userId } = req.cookies
    if(!userId)
        return res.json({code: 1, message: '未知异常'})
    //{'$set', {}}
    User.findOneAndUpdate( { _id: userId }, req.body, (err, doc) => {
        if(err)
            return next(err)
        User.findById({_id: userId }, filter, (err,doc) => {
            if(err) return next(err)
            res.json({code: 0, message: '保存成功', user: doc._doc})
        })
    })
})




module.exports = router